package com.zll.dms.shiro;

import com.zll.dms.mapper.UserMapper;
import com.zll.dms.model.Permission;
import com.zll.dms.model.Role;
import com.zll.dms.model.User;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //用户名作为身份信息
        String userName = (String) principalCollection.getPrimaryPrincipal();
        List<User> userFull = userMapper.getUserFullByName(userName);
        if (CollectionUtils.isNotEmpty(userFull)) {
            User user = userFull.get(0);
            List<Role> roleList = user.getRoleList();
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            if (CollectionUtils.isNotEmpty(roleList)) {
                authorizationInfo.addRoles(roleList.stream().map(Role::getValue).collect(Collectors.toSet()));
                for (Role role : roleList) {
                    List<Permission> permissionList1 = role.getPermissionList();
                    if (CollectionUtils.isNotEmpty(permissionList1)) {
                        //角色中拥有的权限
                        authorizationInfo.addStringPermissions(permissionList1.stream().map(Permission::getValue).collect(Collectors.toSet()));
                    }
                }
            }
            return authorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        List<User> users = userMapper.getUserByName(userName);
        if (CollectionUtils.isNotEmpty(users)) {
            User user = users.get(0);
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), this.getClass().getSimpleName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
